const mongoose = require("mongoose")
const Schema = mongoose.Schema

const TicketSchema = new Schema({
  name: String,
  ticket: String,
  expires_in: Number,
  meta: {
    createAt: {
      type: Date,
      default: Date.now()
    },
    updateAt: {
      type: Date,
      default: Date.now()
    }
  }
})

TicketSchema.pre("save", function(next) {
  if (this.isNew) {
    this.meta.createAt = this.meta.updateAt = Date.now()
  } else {
    this.meta.updateAt = Date.now()
  }
  next()
})

TicketSchema.statics = {
  async getTicket() {
    const token =await this.findOne({ name: "ticket" }).exec()
    return token
  },
  async saveTicket(data) {
    const token =await this.findOne({ name: "ticket" }).exec()
    const { ticket, expires_in } = data
    const _token = new Token({
      name:"ticket",
      ticket,
      expires_in
    })
    try {
      if(!token){
        await _token.save()
        console.log("保存成功")
      }else{
        await this.updateOne(
          {name:"ticket"},
          {$set:{ticket,expires_in}}
        )
        console.log("更新成功")
      }
    } catch (e) {
      console.log("储存失败")
      console.log(e)
    }
  }
}

const Token = mongoose.model("Ticket", TicketSchema)
